package com.ufox.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import com.ufox.entity.CatpachImg;
import com.ufox.entity.Result;
import com.ufox.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

//实现验证码功能
@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {

    @Autowired
    private RedisUtils redisUtils;

    @GetMapping("/getcode")
    @ResponseBody
    public Result GetCode() throws IOException {
//        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 34);
        CircleCaptcha lineCaptcha = CaptchaUtil.createCircleCaptcha(100, 40, 4, 20);
        BufferedImage image = lineCaptcha.getImage();
        String code = lineCaptcha.getCode();
        log.info(code);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        String base64 = Base64.encode(stream.toByteArray());

        // ImgUtil.toBase64(image,"png");


        String uuid = IdUtil.simpleUUID();
        redisUtils.set(uuid, code, 60);
        return Result.ok(new CatpachImg(uuid, base64));
    }
}
